<template>
  <div>
    <video ref="video" controls autoplay style="width: 640px; height: 360px; background: #000;"></video>
    <div style="margin-top: 16px;">
      <button class="flv-btn play" @click="handlePlay" :disabled="playing">播放</button>
      <button class="flv-btn stop" @click="handleStop" :disabled="!playing" style="margin-left: 16px;">停止</button>
    </div>
  </div>
</template>

<script>
import Hls from 'hls.js'

export default {
  name: 'FlvPlayer',
  props: {
    wsUrl: {
      type: String,
      default: '/flv.ts'
    }
  },
  data() {
    return {
      playing: false,
      hls: null
    }
  },
  beforeDestroy() {
    if (this.hls) {
      this.hls.destroy()
      this.hls = null
    }
  },
  methods: {
    async handlePlay() {
      try {
        const res = await fetch('/play', { method: 'POST' })
        const fileName = await res.text()
        setTimeout(() => {
          this.startHls('/file/flv/' + fileName)
        }, 8000)
      } catch (e) {
        console.error('启动播放失败', e)
      }
    },
    async handleStop() {
      try {
        await fetch('/destroy', { method: 'POST' })
      } catch (e) {
        console.error('停止播放失败', e)
      }
      this.stopHls()
    },
    startHls(url) {
      if (this.playing) return
      const video = this.$refs.video
      if (Hls.isSupported()) {
        this.hls = new Hls()
        this.hls.loadSource(url)
        this.hls.attachMedia(video)
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          video.play()
        })
        this.playing = true
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url
        video.addEventListener('loadedmetadata', function () {
          video.play()
        })
        this.playing = true
      } else {
        console.error('当前浏览器不支持 HLS 播放！')
      }
    },
    stopHls() {
      if (this.hls) {
        this.hls.destroy()
        this.hls = null
      }
      const video = this.$refs.video
      video.pause()
      video.removeAttribute('src')
      video.load()
      this.playing = false
    }
  }
}
</script>

<style scoped>
.flv-btn {
  color: #fff;
  border: none;
  padding: 8px 24px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}
.flv-btn.play {
  background: #42b983;
}
.flv-btn.stop {
  background: #e74c3c;
}
.flv-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style> 